#include <unistd.h>
#include <pthread.h>

#include "msg_task.h"
#include "log.h"
#include "task_manager.h"
#include "msg.h"
#include "task.h"

#define USLEEP_TIME_MSG_TASK 100000

int msg_ops(struct msg *msg)
{
	log_info("begin msg_ops in task msg_task.");

	return 0;
}

void *msg_loop(void *data)
{
	log_info("begin msg_loop.");

	while (1) {
		struct task_manager *task_manager = core_conf.task_manager;
		int ut = core_conf.usleep_time >= USLEEP_TIME_MSG_TASK ? core_conf.usleep_time : USLEEP_TIME_MSG_TASK;
	
		if (task_manager == NULL) {
			log_error("task_manager is NULL.");
			usleep(ut);
			continue;
		}

		pthread_mutex_lock(&(task_manager->lock));
		if (task_manager->count == 0) {
			pthread_mutex_unlock(&(task_manager->lock));
			usleep(ut);
			continue;
		}
		struct task *task = task_manager->task_head;

		for (; task != NULL; task = task->next) {

			struct msg *msg;
			int err = 0;

			if (task->msg_queue_request->count == 0) {
				continue;	
			}

			if (task->msg_queue_request->count != 0) {
				err = get_request_msg(&msg, task->task_name);
				if (err != 0) {
					log_error("get_request_msg failed. err = %d", err);
					continue;
				}
			}

			err = task->msg_ops(msg);
			if (err != 0) {
				log_error("task->msg_ops failed. err = %d, task_name: %s", err, task->task_name);
				continue;
			}
		}

		pthread_mutex_unlock(&(task_manager->lock));
		usleep(ut);
	}
}
